// pages/login/login.js
import http from '../../utils/http.js'

Page({
  onLoad(options) {
    const token = getApp().globalData.token;
    const isLoggedIn = getApp().globalData.isLoggedIn;
    if (token && isLoggedIn) {
      wx.switchTab({
        url: '/pages/index/index'
      });
    }
  },

  handleLogin() {
    wx.login({
      success: res => {
        if (res.code) {
          const code = res.code;
          console.log('code='+code)
          // 这里应向后端发送code换取openid和session_key
          // 示例中暂存到全局数据
          http.request({
            url: '/api/login',
            method: 'POST',
            data: {
              code: code
            }
          }).then(res => {
            console.log('token='+res.data.token)
            const token = res.data.token;
            getApp().globalData.token = token;
            getApp().globalData.isLoggedIn = true;
            
            // 登录成功后跳转回首页
            const redirectUrl = this.options.redirect || '/pages/index/index';
wx.reLaunch({
  url: redirectUrl.startsWith('/') ? redirectUrl : `/${redirectUrl}`
});
wx.setStorageSync('token', token);
          }).catch(err => {
            wx.showToast({
  title: '网络请求失败',
  icon: 'none'
});
wx.setStorageSync('token', '');
getApp().globalData.token = '';
getApp().globalData.isLoggedIn = false;
          });
        }
      }
    })
  },

  onGetUserInfo(e) {
    const userInfo = e.detail.userInfo;
    if (userInfo) {
      // 存储用户信息到全局数据
      getApp().globalData.userInfo = userInfo;
    }
  }
})